#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <strings.h>
#include "Log.h"
#include "HttpResponse.h"
#include "TcpConnection.h"

#define ResHeaderszie 16
struct HttpResponse *httpResponseInit()
{
    struct HttpResponse *httpResponse = (struct HttpResponse *)malloc(sizeof(struct HttpResponse));
    httpResponse->headerNum = 0;
    httpResponse->headers = (struct HttpResponseHeader *)malloc(sizeof(struct HttpResponseHeader) * ResHeaderszie);
    httpResponse->statusCode = UNKnown;
    httpResponse->sendDataFunc = NULL;
    // 初始化数组
    bzero(httpResponse->headers, sizeof(struct HttpResponseHeader) * ResHeaderszie);
    bzero(httpResponse->statusMsg, sizeof(httpResponse->statusMsg));
    bzero(httpResponse->fileName, sizeof(httpResponse->fileName));

    return httpResponse;
}

void httpResponseDestory(struct HttpResponse *response)
{
    if (response != NULL)
    {
        if (response->headers != NULL)
        {
            free(response->headers);
        }
        free(response);
    }
}

void httpResponseAddHeader(struct HttpResponse *response, const char *key, const char *value)
{
    if(response == NULL || key == NULL || value == NULL)
    {
        return;
    }
    strncpy(response->headers[response->headerNum].key, key, strlen(key));
    strncpy(response->headers[response->headerNum].value, value, strlen(value));
    response->headerNum++;
}

void httpResponsePrepareMsg(struct HttpResponse *response, struct Buffer *sendBuf, int32_t socket)
{
    //状态行
    char tmp[1024] = {0};
    snprintf(tmp, sizeof(tmp), "HTTP/1.1 %d %s\r\n", response->statusCode, response->statusMsg);
    bufferAppendString(sendBuf, tmp);
    bzero(tmp, sizeof(tmp));
    //响应头
    for(int32_t i = 0; i < response->headerNum; ++i)
    {
        sprintf(tmp, "%s: %s\r\n", response->headers[i].key, response->headers[i].value);
        bufferAppendString(sendBuf, tmp);
        bzero(tmp, sizeof(tmp));
    }
    //空行
    bufferAppendString(sendBuf, "\r\n");
    //回复的数据
    response->sendDataFunc(response->fileName, sendBuf, socket);
}
